package es

import (
	"context"
	"encoding/json"
	"fmt"
	es "github.com/olivere/elastic/v7"
	"strconv"
)

/**
es 增删改查
*/

//index
func Index(u *User) {
	InitClient()

	id := strconv.Itoa(u.ID)

	indexResponse, err := cli.Index().
		Index(indexUser).
		Id(id).
		BodyJson(u).
		Do(context.Background())
	CheckErr(err)

	fmt.Println(indexResponse.Index, indexResponse.Id, indexResponse.Result)
}

func toMap(u *User) map[string]interface{} {
	m := map[string]interface{}{
		"id": u.ID,
	}
	if len(u.Name) > 0 {
		m["name"] = u.Name
	}
	if len(u.Profile) > 0 {
		m["profile"] = u.Profile
	}
	if len(u.Sex) > 0 {
		m["sex"] = u.Sex
	}
	if len(u.Birthday) > 0 {
		m["birthday"] = u.Birthday
	}
	if u.Age != 0 {
		m["age"] = u.Age
	}

	return m
}

//update
func Update(u *User) {
	InitClient()
	id := strconv.Itoa(u.ID)

	m := toMap(u)
	updateResp, err := cli.Update().
		Index(indexUser).
		Id(id).
		Doc(m).
		Do(context.Background())
	CheckErr(err)
	fmt.Println(updateResp.Index, updateResp.Id, updateResp.Result)
}

//delete
func Delete(id string) {
	InitClient()

	deleteResp, err := cli.Delete().
		Index(indexUser).
		Id(id).
		Do(context.Background())
	CheckErr(err)

	fmt.Println(deleteResp.Index, deleteResp.Id, deleteResp.Result)
}

func Get(id string) *User {
	InitClient()

	resp, err := cli.Get().
		Index(indexUser).
		Id(id).
		Do(context.Background())

	if err1, ok := err.(*es.Error); ok {
		if err1.Status == 404 {
			return nil
		}
	}
	CheckErr(err)

	if !resp.Found {
		return nil
	}
	var u = User{}
	err = json.Unmarshal(resp.Source, &u)
	CheckErr(err)

	return &u
}

//bulkIndex
func BulkIndex(users []*User) {
	InitClient()

	bulkService := cli.Bulk()
	for _, u := range users {
		bulkService.Add(es.NewBulkIndexRequest().
			Index(indexUser).
			Id(strconv.Itoa(u.ID)).
			Doc(u))
	}

	bulkResp, err := bulkService.Do(context.Background())
	CheckErr(err)

	fmt.Println(bulkResp.Errors)
}

//bulkDelete
func BulkDelete(ids []string) {
	InitClient()

	bulkService := cli.Bulk()
	for _, id := range ids {
		bulkService.Add(es.NewBulkDeleteRequest().Index(indexUser).Id(id))
	}

	bulkResp, err := bulkService.Do(context.Background())
	CheckErr(err)

	fmt.Println(bulkResp.Errors)
}

//批量获取
func MultiGet(ids []string) []*User {
	InitClient()

	q := es.NewIdsQuery().Ids(ids...)
	searchResult, err := cli.Search(indexUser).Query(q).Do(context.Background())
	CheckErr(err)

	var size = len(searchResult.Hits.Hits)
	users := make([]*User, size, size)
	if size > 0 {
		for i, hit := range searchResult.Hits.Hits {
			var u User
			json.Unmarshal(hit.Source, &u)
			users[i] = &u
		}
	}

	return users
}
